<template>
  <div class="app-container">
    <common-table
      :colnames="colnames"
      :list-data="listData"
      :list-loading="listLoading"
      :is-multiple="isMultiSelect"
      :custom-buttons="customButtons"
      @fetchData="fetchData"
      @itemNew="itemNew"
      @itemEdit="itemEdit"
      @itemDelete="itemDelete"
      @onItemClick="onItemClick"
      @onCustomButtonClick="onCustomButtonClick"
    >
      <!-- <h2>{{ stationName }}</h2> -->
    </common-table>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      destroy-on-close
      width="40%"
    >
      <common-edit
        :fields="editCols"
        :edit-type="editType"
        :values="editValues"
        :rules="editRules"
        @onCancel="dialogVisible = false"
        @onSubmit="onSubmit"
      />
    </el-dialog>

    <el-dialog
      title="修改密码"
      :visible.sync="cpDialog.visible"
      destroy-on-close
      width="40%"
    >
      <reset-password
        :values="cpDialog.values"
        @onCancel="cpDialog.visible = false"
        @onSubmit="onChangePasswordSubmit"
      />
    </el-dialog>

  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import CommonTable from '../commontable'
import CommonEdit from '../commontable/edit'
// import ChangePassword from './changepassword'
import ResetPassword from './resetpassword'
import { getUserList, delUser, addUser, putUser, resetPassword } from '@/api/user'
import { batchDel } from '@/utils'

export default {
  name: 'Users',
  components: { CommonTable, CommonEdit, ResetPassword },
  data() {
    var validatePassword = (rule, value, callback) => {
      if (value !== '') {
        if (value.length < 8) {
          callback(new Error('请输入至少8位的密码'))
          return false
        } else if (
          !/^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,18}$/.test(value)
        ) {
          callback(new Error('密码必须包含大小写字母、数字和特殊字符(@$!%*?&)'))
          return false
        } else {
          callback()
        }
      }
    }
    return {
      customButtons: [
        { name: '重置密码', isMultiSelect: false, data: {}}
      ],
      colnames: [
        { displayName: '序号', colName: 'id', dataType: 'indexNo', colWidth: '64px', sortable: 'custom' },
        { displayName: '登录名', colName: 'loginName', sortable: 'custom' },
        { displayName: '显示昵称', colName: 'userName', sortable: 'custom' },
        { displayName: '头像', colName: 'avatarUrl', sortable: false, hidden: true },
        { displayName: '邮箱', colName: 'email', sortable: 'custom' },
        { displayName: '性别', colName: 'gender', sortable: 'custom', dataType: 'gender' },
        { displayName: '手机号', colName: 'telNumber', sortable: 'custom' },
        { displayName: '角色', colName: 'roles', sortable: false }
      ],
      editCols: [
        { displayName: 'ID', colName: 'id', colWidth: '64px', readOnly: true, sortable: 'custom' },
        { displayName: '登录名', colName: 'loginName', sortable: 'custom', readOnly: true },
        { displayName: '密码', colName: 'password', dataType: 'password', hiddenIn: 'edit' },
        { displayName: '显示昵称', colName: 'userName', sortable: 'custom' },
        { displayName: '邮箱', colName: 'email', sortable: 'custom' },
        { displayName: '性别', colName: 'gender', sortable: 'custom', dataType: 'select', data: {
          options: [
            { name: '女', value: 0 },
            { name: '男', value: 1 },
            { name: '保密', value: 2 }
          ]
        }},
        { displayName: '手机号', colName: 'telNumber', sortable: 'custom' }
      ],
      editType: 'edit',
      editValues: {},
      listData: {},
      editRules: {
        'loginName': [{ required: true, message: '不能为空' }],
        'password': [{ required: true, message: '请输入密码' }, { validator: validatePassword, trigger: 'blur' }],
        'userName': [{ required: true, message: '不能为空' }],
        'gender': [{ required: true, message: '不能为空' }],
        'email': [{ required: true, type: 'email', message: '请输入正确的邮箱', trigger: 'blur' }],
        'telNumber': [{ required: true, message: '不能为空' }]
      },
      listLoading: false,
      isMultiSelect: false,
      dialogVisible: false,
      dialogTitle: '新建',
      stationName: '用户管理',
      listQuery: {},
      cpDialog: {
        visible: false,
        values: {}
      }
    }
  },
  computed: {
    ...mapGetters([
      'user',
      'name',
      'avatar',
      'roles'
    ])
  },
  created() {
  },
  mounted() {
    this.$nextTick(() => {
      // if (this.$route.params.stationName) {
      //   this.stationName = this.$route.params.stationName + ' 设备'
      // }
    })
  },
  methods: {
    fetchData(listQuery) {
      this.listQuery = listQuery
      console.log('fetchData', listQuery)
      this.listLoading = true
      getUserList(listQuery, this.$route.params.stationId)
        .then(ret => {
          console.log('ret', ret)
          this.listData = ret.data
        }).finally(() => {
          this.listLoading = false
        })
    },
    itemNew() {
      console.log('etag New', this.$route.params.stationId)
      this.editType = 'add'
      this.dialogTitle = '新建'
      this.editValues = {
        stationId: this.$route.params.stationId
      }
      this.editCols[1].readOnly = false
      this.dialogVisible = true
    },
    itemEdit({ type, item, items }) {
      console.log('itemEdit')
      this.editType = 'edit'
      this.editValues = item
      this.dialogTitle = '修改'
      this.editCols[1].readOnly = true
      this.dialogVisible = true
    },
    itemDelete({ type, item, items }) {
      console.log('itemDelete')
      if (type === 'one') {
        delUser({ userId: item.id }).then(ret => {
          this.$message({
            type: 'success',
            message: '删除成功！'
          })
          this.fetchData(this.listQuery)
        })
      } else if (type === 'multi') {
        batchDel(delUser, items, { idname: 'userId', idvalue: 'id' }).then(ret => {
          this.$message({
            type: 'success',
            message: '删除成功！'
          })
          this.fetchData(this.listQuery)
        })
      }
    },
    onSubmit(formData) {
      console.log('onSubmit', formData)
      if (this.editType === 'add') {
        // 新建
        addUser(formData).then((ret) => {
          console.log('add ret', ret)
          this.$message({
            type: 'success',
            message: '添加成功！'
          })
          this.dialogVisible = false
          this.fetchData(this.listQuery)
        })
      } else {
        // 修改
        putUser(formData).then((ret) => {
          console.log('edit ret', ret)
          this.$message({
            type: 'success',
            message: '修改成功！'
          })
          this.dialogVisible = false
          this.fetchData(this.listQuery)
        })
      }
    },
    onItemClick({ col, row }) {
      // 点击事件
      if (col.link) {
        if (col.link.name === 'priceDetail') {
          // 价格牌详情
          console.log('priceDetail', row)
        }
      }
    },
    onCustomButtonClick({ target, data }) {
      // 自定义按钮点击事件
      if (target.name === '重置密码') {
        if (!data.item.id) {
          this.$message({
            message: '请先选择一条记录再修改密码!',
            type: 'warning'
          })
          return
        }
        this.cpDialog.values = { ...data.item }
        this.cpDialog.visible = true
      }
    },
    onChangePasswordSubmit(formData) {
      resetPassword(formData).then(ret => {
        console.log('ResetPassword ret', ret)
        this.$message({
          type: 'success',
          message: '修改成功！'
        })
        this.cpDialog.visible = false
      })
    }
  }
}
</script>
